package org.shoukaiseki.test.spring.multiple.datasource.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.shoukaiseki.test.spring.multiple.datasource.config.annotation.DataSourceOne;
import org.shoukaiseki.test.spring.multiple.datasource.config.annotation.DataSourceZero;
import org.shoukaiseki.test.spring.multiple.datasource.config.constant.BeanConstants;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.inject.Named;
import javax.sql.DataSource;

/**
 * org.shoukaiseki.test.spring.multiple.datasource.config.OneDataSourceConfig <br>
 *
 * @author 蒋カイセキ    Japan-Tokyo  2018-09-10 11:37:03<br>
 * ブログ http://shoukaiseki.blog.163.com/<br>
 * E-メール jiang28555@Gmail.com<br>
 **/
@Configuration
@MapperScan(annotationClass = DataSourceZero.class,basePackages = "org.shoukaiseki.test",sqlSessionFactoryRef = BeanConstants.ZERO_SQLSESSION_FACTORY)
public class ZeroDataSourceConfig {


    @Value(BeanConstants.MAPPER_LOCATION)
    String mapperLocation;

    public ZeroDataSourceConfig(){
        System.out.println("------------------- OneDataSourceConfig");
    }


    @Bean(name = BeanConstants.ZERO_DATASOURCE, destroyMethod = "")
    @Primary
    @ConfigurationProperties(prefix = "sks.multiple.datasource.zero")
    public DataSource dataSource() {
        // 属性由springboot自动填写
        return new DruidDataSource();
    }


    @Bean(BeanConstants.ZERO_SQLSESSION_FACTORY)
    @Primary
    public SqlSessionFactory sqlSessionFactory(@Named(BeanConstants.ZERO_DATASOURCE) final DataSource dataSourceOne) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSourceOne);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapperLocation));
        return bean.getObject();
    }

    @Bean(BeanConstants.ZERO_DATASOURCE+"Transaction")
    @Primary
    public PlatformTransactionManager transactionManager(@Named(BeanConstants.ZERO_DATASOURCE)DataSource dataSourceOne) {
        return new DataSourceTransactionManager(dataSourceOne);
    }

}
